<template>
  <div class="modal">
    <!-- 遮罩 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginBox">
      <!-- 关闭图标 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <nav class="nav">
        <a href="#" @click="IsShowPhoneLogin = true">手机号码登录</a>|
        <a href="#" @click="showQrCode" :class="{ active: IsShowPhoneLogin }"
          >微信扫码登录</a
        >
      </nav>
      <!-- 内容 -->
      <div class="content">
        <!--手机号登录内容  -->
        <div class="phoneLogin" v-show="IsShowPhoneLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgs"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" placeholder="请输入验证码" v-model="yzmCode" />
            <button class="btn btnCode" @click="getCode" v-show="isShowCount">
              获取验证码
            </button>
            <button class="btn btnCode" @click="getCode" v-show="!isShowCount">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnLogin" @click="getLogin">登录</button>
          </div>
        </div>
        <!-- wx扫码登录框 -->
        <div class="qrLogin">
          <div id="weixin" class="qrcode" v-show="!IsShowPhoneLogin">
            二维码
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import {
  SendSMSAPI,
  PhoneReginAPI,
  BindingAPI,
  UserProfilesAPI,
} from "@/require/api";
import { validatePhoneNumber } from "@/utils/index";
export default {
  data() {
    return {
      // 手机号登录框展示
      IsShowPhoneLogin: true,
      // 滑动数据
      msg: "向右滑动",
      // 滑动图片
      imgs: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("@/assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
      ],
      phoneNumber: "",
      // 倒计时
      count: 5,
      // 控制倒计时是否显示
      isShowCount: true,
      // 验证码
      yzmCode: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),

    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 获取验证码
    async getCode() {
      // 调用校验
      if (!this.toVerify()) return;
      // 3.请求后台发送短信
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      console.log("短信", res);
      // 4.获取成功，倒计时，不让按钮可以疯狂点
      if (res.code == 0) {
        this.isShowCount = false;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.isShowCount = true;
            this.count = 5;
          }
        }, 1000);
      }
    },

    // 统一校验手机号和滑块
    toVerify() {
      // 1.获取正确的手机号
      if (!validatePhoneNumber(this.phoneNumber)) {
        // 在toast中显示
        this.asyncShowToast({
          isShow: true,
          title: "请输入正确手机号",
          type: "warnning",
        });
        return;
      }
      // 2.滑动滑块
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        this.asyncShowToast({
          isShow: true,
          title: "请滑动滑块",
          type: "warnning",
        });
        return;
      }
      return true;
    },

    // 登录
    async getLogin() {
      // 1.调用统一校验手机号和短信验证码
      if (!this.toVerify()) return;
      // 3.判断短信非空
      if (this.yzmCode == "") {
        alert("请输入短信验证码");
        return;
      }
      // 4.发起登录请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        // 如果有uuid 则手机绑定微信登录请求
        res = await BindingAPI({
          verifyCode: this.yzmCode,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        // 没有uuid 普通手机号码登录请求
        res = await PhoneReginAPI({
          verifyCode: this.yzmCode,
          phone: this.phoneNumber,
        });
      }
      if (!res) return;
      if (res.code == 0) {
        // 1.提示登录成功
        this.asyncShowToast({
          isShow: true,
          title: "登陆成功",
          type: "success",
        });
        // 2.存储token 为了证明已经登陆过
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 3.隐藏登录框
        this.changeIsShowLoginModal(false);
      }
      // 4.切换登录状态到购物车
      this.changeIsLogined(true);
      // 5.清除uuid
      localStorage.removeItem("uuid");
      // 同步用户信息
      this.asyncChangeUserInfo();
    },
    // 微信二维码扫码登录
    showQrCode() {
      this.IsShowPhoneLogin = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 16px;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
    }
    .nav {
      text-align: center;
      margin-top: 30px;
      font-size: 20px;
    }
    .content {
      .phoneLogin {
        .row {
          width: 355px;
          height: 50px;
          display: flex;
          margin-top: 30px;
          margin-left: 99px;
          input {
            flex: 1;
          }
          .btn {
            background-color: #2853c2;
            color: aliceblue;
          }
          .btnCode {
            margin-left: 10px;
            width: 88px;
          }
          .btnLogin {
            flex: 1;
            height: 50px;
          }
        }
      }
      .qrLogin {
        #weixin {
          /* background-color: #fcf; */
          justify-content: center;
          margin-top: 20px;
          display: flex;
        }
      }
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>